<template>
  <div class="transaction-analysis">
    <el-skeleton :rows="10" animated v-if="loading" />
    
    <template v-else>
      <!-- 交易概览表格 -->
      <el-card class="table-card" shadow="hover">
        <template #header>
          <div class="card-header">
            <span>交易概览数据</span>
          </div>
        </template>
        
        <el-table :data="transactionOverviewData" style="width: 100%" border stripe>
          <el-table-column prop="name" label="指标名称" width="180" />
          <el-table-column prop="value" label="当前值" width="180">
            <template #default="scope">
              <span :class="{ 'value-growth': scope.row.isGrowth }">{{ scope.row.value }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="lastPeriod" label="上期值" width="180" />
          <el-table-column prop="growth" label="环比增长" width="180">
            <template #default="scope">
              <el-tag v-if="scope.row.growth" size="small" :type="scope.row.growth >= 0 ? 'success' : 'danger'">
                {{ scope.row.growth >= 0 ? '+' : '' }}{{ scope.row.growth }}%
              </el-tag>
              <span v-else>-</span>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
      
      <!-- 交易趋势图 -->
      <el-card class="chart-card" shadow="hover">
        <template #header>
          <div class="card-header">
            <span>交易趋势分析</span>
            <div class="chart-controls">
              <el-radio-group v-model="trendTimeUnit" size="small" @change="updateTrendChart">
                <el-radio-button label="day">日</el-radio-button>
                <el-radio-button label="week">周</el-radio-button>
                <el-radio-button label="month">月</el-radio-button>
              </el-radio-group>
            </div>
          </div>
        </template>
        <div class="chart-container" ref="transactionTrendChart"></div>
      </el-card>
      
      <!-- 支付方式表格 -->
      <el-card class="table-card" shadow="hover">
        <template #header>
          <div class="card-header">
            <span>支付方式分布</span>
          </div>
        </template>
        
        <el-table :data="paymentMethodDistribution" style="width: 100%" border stripe>
          <el-table-column prop="method" label="支付方式" width="180" />
          <el-table-column prop="amount" label="交易金额" width="180">
            <template #default="scope">
              ¥{{ formatNumber(scope.row.amount) }}
            </template>
          </el-table-column>
          <el-table-column prop="count" label="交易笔数" width="180" />
          <el-table-column prop="ratio" label="交易占比" width="180">
            <template #default="scope">
              {{ calculateRatio(scope.row.amount) }}%
            </template>
          </el-table-column>
        </el-table>
      </el-card>
      
      <!-- 交易时段表格 -->
      <el-card class="table-card" shadow="hover">
        <template #header>
          <div class="card-header">
            <span>交易时段分布</span>
          </div>
        </template>
        
        <el-table :data="hourlyDistribution" style="width: 100%" border stripe>
          <el-table-column prop="hour" label="时段" width="180">
            <template #default="scope">
              {{ scope.row.hour }}:00
            </template>
          </el-table-column>
          <el-table-column prop="amount" label="交易金额" width="180">
            <template #default="scope">
              ¥{{ formatNumber(scope.row.amount) }}
            </template>
          </el-table-column>
          <el-table-column prop="count" label="交易笔数" width="180" />
          <el-table-column prop="ratio" label="交易占比" width="180">
            <template #default="scope">
              {{ calculateTimeRatio(scope.row.count) }}%
            </template>
          </el-table-column>
        </el-table>
      </el-card>
      
      <!-- 交易详情表格 -->
      <el-card class="table-card" shadow="hover">
        <template #header>
          <div class="card-header">
            <span>交易详情列表</span>
            <div class="table-actions">
              <el-input 
                v-model="searchKeyword" 
                placeholder="搜索交易号/会员" 
                clearable 
                @input="handleSearch"
                class="search-input"
              >
                <template #prefix>
                  <el-icon><Search /></el-icon>
                </template>
              </el-input>
              
              <el-select v-model="filterPaymentMethod" placeholder="支付方式" clearable @change="handleFilter">
                <el-option
                  v-for="method in paymentMethods"
                  :key="method.value"
                  :label="method.label"
                  :value="method.value"
                />
              </el-select>
              
              <el-select v-model="sortBy" placeholder="排序方式" @change="handleSort">
                <el-option label="交易时间 (新到旧)" value="time-desc" />
                <el-option label="交易时间 (旧到新)" value="time-asc" />
                <el-option label="交易金额 (高到低)" value="amount-desc" />
                <el-option label="交易金额 (低到高)" value="amount-asc" />
                <el-option label="商品数量 (多到少)" value="items-desc" />
                <el-option label="商品数量 (少到多)" value="items-asc" />
              </el-select>
            </div>
          </div>
        </template>
        
        <el-table :data="displayedTransactions" stripe style="width: 100%">
          <el-table-column prop="id" label="交易号" width="120" />
          <el-table-column prop="time" label="交易时间" width="180" sortable />
          <el-table-column prop="amount" label="交易金额" width="120" sortable>
            <template #default="scope">
              ¥{{ formatNumber(scope.row.amount) }}
            </template>
          </el-table-column>
          <el-table-column prop="items" label="商品数量" width="100" sortable />
          <el-table-column prop="paymentMethod" label="支付方式" width="120" />
          <el-table-column prop="memberName" label="会员信息" min-width="150">
            <template #default="scope">
              <template v-if="scope.row.memberId">
                {{ scope.row.memberName }}
                <el-tag size="small" type="success">会员</el-tag>
              </template>
              <template v-else>
                <el-tag size="small" type="info">非会员</el-tag>
              </template>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="120">
            <template #default="scope">
              <el-button 
                type="primary" 
                size="small" 
                @click="viewTransactionDetails(scope.row)"
                text
              >
                详情
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        
        <div class="pagination-container">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="filteredTransactions.length"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>
    </template>
    
    <!-- 交易详情弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      title="交易详情"
      width="600px"
    >
      <template v-if="selectedTransaction">
        <div class="transaction-info">
          <div class="info-row">
            <span class="info-label">交易号:</span>
            <span class="info-value">{{ selectedTransaction.id }}</span>
          </div>
          <div class="info-row">
            <span class="info-label">交易时间:</span>
            <span class="info-value">{{ selectedTransaction.time }}</span>
          </div>
          <div class="info-row">
            <span class="info-label">交易金额:</span>
            <span class="info-value">¥{{ formatNumber(selectedTransaction.amount) }}</span>
          </div>
          <div class="info-row">
            <span class="info-label">支付方式:</span>
            <span class="info-value">{{ selectedTransaction.paymentMethod }}</span>
          </div>
          <div class="info-row">
            <span class="info-label">收银员:</span>
            <span class="info-value">{{ selectedTransaction.cashier }}</span>
          </div>
          <div class="info-row" v-if="selectedTransaction.memberId">
            <span class="info-label">会员信息:</span>
            <span class="info-value">
              {{ selectedTransaction.memberName }} ({{ selectedTransaction.memberPhone }})
            </span>
          </div>
          <div class="info-row" v-if="selectedTransaction.couponAmount">
            <span class="info-label">优惠金额:</span>
            <span class="info-value">¥{{ formatNumber(selectedTransaction.couponAmount) }}</span>
          </div>
        </div>
        
        <div class="transaction-items">
          <h4>商品明细</h4>
          <el-table :data="selectedTransaction.items || []" stripe style="width: 100%">
            <el-table-column prop="name" label="商品名称" min-width="150" />
            <el-table-column prop="price" label="单价" width="100">
              <template #default="scope">
                ¥{{ formatNumber(scope.row.price) }}
              </template>
            </el-table-column>
            <el-table-column prop="quantity" label="数量" width="80" />
            <el-table-column prop="subtotal" label="小计" width="120">
              <template #default="scope">
                ¥{{ formatNumber(scope.row.subtotal) }}
              </template>
            </el-table-column>
          </el-table>
        </div>
      </template>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="printTransaction">打印小票</el-button>
          <el-button @click="dialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch, nextTick } from 'vue'
import { Search } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import * as echarts from 'echarts/core'
import { BarChart, LineChart, PieChart } from 'echarts/charts'
import {
  TitleComponent,
  TooltipComponent,
  GridComponent,
  LegendComponent,
  DataZoomComponent
} from 'echarts/components'
import { CanvasRenderer } from 'echarts/renderers'

// 注册必要的组件
echarts.use([
  BarChart,
  LineChart,
  PieChart,
  TitleComponent,
  TooltipComponent,
  GridComponent,
  LegendComponent,
  DataZoomComponent,
  CanvasRenderer
])

const props = defineProps({
  dateRange: {
    type: Array,
    required: true
  },
  loading: {
    type: Boolean,
    default: false
  },
  reportData: {
    type: Object,
    default: () => ({})
  }
})

// 图表引用
const transactionTrendChart = ref(null)
const paymentMethodChart = ref(null)
const hourlyTransactionChart = ref(null)

// 图表实例
let transactionTrendChartInstance = null
let paymentMethodChartInstance = null
let hourlyTransactionChartInstance = null

// 表格数据和分页
const searchKeyword = ref('')
const sortBy = ref('time-desc')
const filterPaymentMethod = ref('')
const currentPage = ref(1)
const pageSize = ref(10)
const trendTimeUnit = ref('day')

// 交易详情弹窗
const dialogVisible = ref(false)
const selectedTransaction = ref(null)

// 计算属性 - 从报表数据中提取需要的数据
const totalTransactions = computed(() => props.reportData.totalTransactions || 0)
const avgTransactionAmount = computed(() => props.reportData.avgTransactionAmount || 0)
const maxTransactionAmount = computed(() => props.reportData.maxTransactionAmount || 0)
const maxTransactionDate = computed(() => props.reportData.maxTransactionDate || '')
const dailyAvgTransactions = computed(() => props.reportData.dailyAvgTransactions || 0)
const peakDailyTransactions = computed(() => props.reportData.peakDailyTransactions || 0)
const transactionGrowth = computed(() => props.reportData.transactionGrowth || 0)
const avgTransactionGrowth = computed(() => props.reportData.avgTransactionGrowth || 0)
const lastPeriodTransactions = computed(() => props.reportData.lastPeriodTransactions || 0)
const lastPeriodAvgAmount = computed(() => props.reportData.lastPeriodAvgAmount || 0)
const transactions = computed(() => props.reportData.transactions || [])
const paymentMethods = computed(() => props.reportData.paymentMethods || [])

// 筛选和排序后的交易数据
const filteredTransactions = computed(() => {
  let result = [...transactions.value]
  
  // 搜索关键词筛选
  if (searchKeyword.value) {
    const keyword = searchKeyword.value.toLowerCase()
    result = result.filter(transaction => 
      transaction.id.toLowerCase().includes(keyword) || 
      (transaction.memberName && transaction.memberName.toLowerCase().includes(keyword))
    )
  }
  
  // 支付方式筛选
  if (filterPaymentMethod.value) {
    result = result.filter(transaction => transaction.paymentMethod === filterPaymentMethod.value)
  }
  
  // 排序
  if (sortBy.value) {
    const [field, order] = sortBy.value.split('-')
    result.sort((a, b) => {
      if (field === 'time') {
        const dateA = new Date(a.time)
        const dateB = new Date(b.time)
        return order === 'asc' ? dateA - dateB : dateB - dateA
      } else {
        return order === 'asc' ? a[field] - b[field] : b[field] - a[field]
      }
    })
  }
  
  return result
})

// 当前页显示的交易
const displayedTransactions = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filteredTransactions.value.slice(start, end)
})

// 格式化数字函数
const formatNumber = (num) => {
  if (num === undefined || num === null) return '0'
  
  // 如果是整数，直接返回
  if (Number.isInteger(num)) return num.toString()
  
  // 否则保留两位小数
  return num.toFixed(2)
}

// 计算交易概览数据表格
const transactionOverviewData = computed(() => {
  return [
    { 
      name: '总交易数', 
      value: formatNumber(totalTransactions.value), 
      lastPeriod: formatNumber(lastPeriodTransactions.value),
      growth: transactionGrowth.value,
      isGrowth: false
    },
    { 
      name: '平均交易额', 
      value: `¥${formatNumber(avgTransactionAmount.value)}`, 
      lastPeriod: `¥${formatNumber(lastPeriodAvgAmount.value)}`,
      growth: avgTransactionGrowth.value,
      isGrowth: false
    },
    { 
      name: '最高交易额', 
      value: `¥${formatNumber(maxTransactionAmount.value)}`, 
      lastPeriod: '无对比',
      growth: null,
      isGrowth: false
    },
    { 
      name: '日均交易量', 
      value: formatNumber(dailyAvgTransactions.value), 
      lastPeriod: '峰值:' + formatNumber(peakDailyTransactions.value),
      growth: null,
      isGrowth: false
    }
  ]
})

// 支付方式分布数据
const paymentMethodDistribution = computed(() => {
  return props.reportData.paymentMethodDistribution || []
})

// 时段交易分布数据
const hourlyDistribution = computed(() => {
  return props.reportData.hourlyDistribution || []
})

// 计算支付方式占比
const calculateRatio = (amount) => {
  if (!amount || !totalTransactions.value) return '0.00'
  const totalAmount = paymentMethodDistribution.value.reduce((sum, item) => sum + item.amount, 0)
  return ((amount / totalAmount) * 100).toFixed(2)
}

// 计算时段交易占比
const calculateTimeRatio = (count) => {
  if (!count || !totalTransactions.value) return '0.00'
  return ((count / totalTransactions.value) * 100).toFixed(2)
}

// 初始化交易趋势图
const initTransactionTrendChart = () => {
  if (!transactionTrendChart.value) return
  
  // 如果图表已经存在，销毁它
  if (transactionTrendChartInstance) {
    transactionTrendChartInstance.dispose()
  }
  
  // 创建新的图表实例
  transactionTrendChartInstance = echarts.init(transactionTrendChart.value)
  
  // 获取数据
  const trendData = props.reportData.transactionTrend || {}
  const trendUnit = trendTimeUnit.value
  const xAxisData = trendData[trendUnit]?.dates || []
  const countData = trendData[trendUnit]?.counts || []
  const amountData = trendData[trendUnit]?.amounts || []
  
  // 图表配置
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross',
        crossStyle: {
          color: '#999'
        }
      }
    },
    legend: {
      data: ['交易笔数', '交易金额']
    },
    xAxis: [
      {
        type: 'category',
        data: xAxisData,
        axisPointer: {
          type: 'shadow'
        }
      }
    ],
    yAxis: [
      {
        type: 'value',
        name: '交易笔数',
        min: 0,
        axisLabel: {
          formatter: '{value}'
        }
      },
      {
        type: 'value',
        name: '交易金额',
        min: 0,
        axisLabel: {
          formatter: '¥{value}'
        }
      }
    ],
    series: [
      {
        name: '交易笔数',
        type: 'bar',
        data: countData
      },
      {
        name: '交易金额',
        type: 'line',
        yAxisIndex: 1,
        data: amountData
      }
    ]
  }
  
  // 设置图表配置
  transactionTrendChartInstance.setOption(option)
  
  // 窗口大小变化时自动调整图表大小
  window.addEventListener('resize', () => {
    transactionTrendChartInstance.resize()
  })
}

// 初始化支付方式分布图
const initPaymentMethodChart = () => {
  if (!paymentMethodChart.value) return
  
  // 如果图表已经存在，销毁它
  if (paymentMethodChartInstance) {
    paymentMethodChartInstance.dispose()
  }
  
  // 创建新的图表实例
  paymentMethodChartInstance = echarts.init(paymentMethodChart.value)
  
  // 获取数据
  const paymentData = props.reportData.paymentMethodDistribution || []
  
  // 将数据转换为饼图需要的格式
  const pieData = paymentData.map(item => ({
    name: item.method,
    value: item.amount
  }))
  
  // 图表配置
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: ¥{c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      right: 10,
      top: 'center',
      data: paymentData.map(item => item.method)
    },
    series: [
      {
        name: '支付方式',
        type: 'pie',
        radius: ['50%', '70%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '14',
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: pieData
      }
    ]
  }
  
  // 设置图表配置
  paymentMethodChartInstance.setOption(option)
  
  // 窗口大小变化时自动调整图表大小
  window.addEventListener('resize', () => {
    paymentMethodChartInstance.resize()
  })
}

// 初始化时段交易分布图
const initHourlyTransactionChart = () => {
  if (!hourlyTransactionChart.value) return
  
  // 如果图表已经存在，销毁它
  if (hourlyTransactionChartInstance) {
    hourlyTransactionChartInstance.dispose()
  }
  
  // 创建新的图表实例
  hourlyTransactionChartInstance = echarts.init(hourlyTransactionChart.value)
  
  // 获取数据
  const hourlyData = props.reportData.hourlyDistribution || []
  
  // 准备数据
  const hours = hourlyData.map(item => `${item.hour}:00`)
  const countData = hourlyData.map(item => item.count)
  const amountData = hourlyData.map(item => item.amount)
  
  // 图表配置
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross',
        crossStyle: {
          color: '#999'
        }
      }
    },
    legend: {
      data: ['交易笔数', '交易金额']
    },
    xAxis: [
      {
        type: 'category',
        data: hours,
        axisPointer: {
          type: 'shadow'
        }
      }
    ],
    yAxis: [
      {
        type: 'value',
        name: '交易笔数',
        min: 0,
        axisLabel: {
          formatter: '{value}'
        }
      },
      {
        type: 'value',
        name: '交易金额',
        min: 0,
        axisLabel: {
          formatter: '¥{value}'
        }
      }
    ],
    series: [
      {
        name: '交易笔数',
        type: 'bar',
        data: countData
      },
      {
        name: '交易金额',
        type: 'line',
        yAxisIndex: 1,
        data: amountData
      }
    ]
  }
  
  // 设置图表配置
  hourlyTransactionChartInstance.setOption(option)
  
  // 窗口大小变化时自动调整图表大小
  window.addEventListener('resize', () => {
    hourlyTransactionChartInstance.resize()
  })
}

// 查看交易详情
const viewTransactionDetails = (transaction) => {
  selectedTransaction.value = transaction
  dialogVisible.value = true
}

// 打印交易小票
const printTransaction = () => {
  ElMessage.success('交易小票打印功能即将上线')
  // 这里可以添加打印小票的功能
}

// 处理搜索
const handleSearch = () => {
  currentPage.value = 1
}

// 处理排序
const handleSort = () => {
  currentPage.value = 1
}

// 处理筛选
const handleFilter = () => {
  currentPage.value = 1
}

// 处理页码变更
const handleCurrentChange = (page) => {
  currentPage.value = page
}

// 处理每页数量变更
const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
}

// 更新趋势图的时间单位
const updateTrendChart = () => {
  initTransactionTrendChart()
}

// 监听数据变化，更新图表
watch(() => props.reportData, () => {
  nextTick(() => {
    initTransactionTrendChart()
    initPaymentMethodChart()
    initHourlyTransactionChart()
  })
}, { deep: true })

// 组件挂载时初始化图表
onMounted(() => {
  if (!props.loading && Object.keys(props.reportData).length > 0) {
    nextTick(() => {
      initTransactionTrendChart()
      initPaymentMethodChart()
      initHourlyTransactionChart()
    })
  }
})

// 组件卸载时清理图表实例
onUnmounted(() => {
  if (transactionTrendChartInstance) {
    transactionTrendChartInstance.dispose()
  }
  if (paymentMethodChartInstance) {
    paymentMethodChartInstance.dispose()
  }
  if (hourlyTransactionChartInstance) {
    hourlyTransactionChartInstance.dispose()
  }
  
  window.removeEventListener('resize', () => {
    if (transactionTrendChartInstance) transactionTrendChartInstance.resize()
    if (paymentMethodChartInstance) paymentMethodChartInstance.resize()
    if (hourlyTransactionChartInstance) hourlyTransactionChartInstance.resize()
  })
})
</script>

<style scoped>
.transaction-analysis {
  width: 100%;
}

.table-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chart-card {
  margin-bottom: 20px;
}

.chart-container {
  height: 400px;
  width: 100%;
}

.value-growth {
  color: #67c23a;
  font-weight: bold;
}

.table-actions {
  display: flex;
  gap: 10px;
}

.search-input {
  width: 200px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.transaction-info {
  margin-bottom: 20px;
}

.info-row {
  display: flex;
  margin-bottom: 10px;
}

.info-label {
  font-weight: bold;
  width: 100px;
}

.transaction-items h4 {
  margin-bottom: 10px;
}

/* 响应式布局 */
@media (max-width: 1200px) {
  .el-table {
    width: 100%;
    overflow-x: auto;
  }
}

@media (max-width: 768px) {
  .el-table {
    width: 100%;
    overflow-x: auto;
  }
  
  .search-input {
    width: 100%;
  }
}
</style> 